<?php

namespace app\common\library;

use think\Db;
use think\Exception;
use think\facade\Hook;

/**
 * 短信验证码类
 */
class Sms
{
    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 600;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    /**
     * ip限制流
     * @var int
     */
    protected static $ipLimitNum = 5;

    /**
     * 获取最后一次手机发送的数据
     * @param $mobile
     * @param string $event
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = Db::name('system_sms')
            ->where(['mobile' => $mobile, 'event' => $event])
            ->order('id desc')
            ->limit(1)
            ->find();
        Hook::listen('sms_get', $sms,  true);
        return $sms ? $sms : NULL;
    }

    /**
     * 发送验证码
     *
     * @param   int $mobile 手机号
     * @param   int $code 验证码,为空时将自动生成4位数字
     * @param   string $event 事件
     * @return bool
     * @throws Exception
     */
    public static function send($mobile, $code = NULL, $event = 'default')
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = Db::name('system_sms')->insert(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'create_time' => $time]);
        if (empty(Hook::get('sms_send'))) {
            throw new Exception('请定义sms_send钩子,用来发送短信！');
        }
        $result = Hook::listen('sms_send', $mobile,  true);
        if (!$result) {
            $sms->delete();
            return FALSE;
        }
        return TRUE;
    }

    /**
     * 发送通知
     *
     * @param   mixed $mobile 手机号,多个以,分隔
     * @param   string $msg 消息内容
     * @param   string $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = NULL)
    {
        $params = [
            'mobile' => $mobile,
            'msg' => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params,  true);
        return $result ? TRUE : FALSE;
    }

    /**
     * 校验验证码
     *
     * @param   int $mobile 手机号
     * @param   int $code 验证码
     * @param   string $event 事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = Db::name('system_sms')->where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if (!$sms) {
            return false;
        }
        if ($sms['create_time'] > $time && $sms['times'] <= self::$maxCheckNums) {
            if ($code != $sms['code']) {
                $sms['times'] = $sms['times'] + 1;
                Db::name('system_sms')
                    ->where('id', $sms['id'])
                    ->update(['times' => $sms['times']]);
                return false;
            }
            if (!empty(Hook::get('sms_check'))) {
                return Hook::listen('sms_check', $sms, true);
            }
            return true;
        }
        // 过期则清空该手机验证码
        self::flush($mobile, $event);
        return false;
    }

    /**
     * 清空指定手机号验证码
     *
     * @param   int $mobile 手机号
     * @param   string $event 事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        Db::name('system_sms')
            ->where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        if (Hook::get('sms_flush')) {
            Hook::listen('sms_flush');
        }
        return TRUE;
    }


    /**
     * 单位时间短信ip限流
     * @return bool
     */
    public static function ipLimit()
    {
        $ipSendTotal = Db::name('system_sms')
            ->where(['ip' => request()->ip()])
            ->whereTime('create_time', '-1 hours')
            ->count();

        if ($ipSendTotal >= self::$ipLimitNum) {
            return false;
        }
        return true;
    }

    /**
     * 高频限流
     * @param $mobile
     * @param $event
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function frequencyLimit($mobile, $event)
    {
        $last = self::get($mobile, $event);
        if (!empty($last)) {
            if($last && time() - $last['create_time'] < 60){
                return false;
            }
        }
        return true;

    }
}
